package com.scott.wechat.controller;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.scott.wechat.model.InputMessage;
import com.scott.wechat.model.MsgType;
import com.scott.wechat.model.OutputMessage;
import com.scott.wechat.service.WechatService;
import com.scott.wechat.util.SerializeXmlUtil;
import com.thoughtworks.xstream.XStream;

@RestController
@RequestMapping("/")
public class CallBackController {
	
	private static Logger LOGGER = LoggerFactory.getLogger(CallBackController.class);
	
	@Autowired
	private WechatService wechatService;
	
	@GetMapping(value = "/echo")
	public Object echo() {
		LOGGER.info("----echo------");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "server up!!!");
		return map;
	}
	
	@GetMapping("/main")
	public void config(HttpServletRequest request, HttpServletResponse response) throws IOException {
		LOGGER.info("第一次配置-{}", request.getRequestURL().toString());
		String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        boolean result = wechatService.checkSignature(signature, timestamp, nonce, echostr);
        if(result) {
        		LOGGER.info("signature={}\ntimestamp={}\nnonce={}\nechostr={}", new Object[] {signature,timestamp,nonce,echostr});
        		response.getWriter().write(echostr);
        }
	}
	
	@PostMapping("/main")
	public void talk(HttpServletRequest request, HttpServletResponse response) throws IOException {
		LOGGER.info("交互-{}", request.getRequestURL().toString());
		// 处理接收消息  
        ServletInputStream in = request.getInputStream();  
        // 将POST流转换为XStream对象  
        XStream xs = SerializeXmlUtil.createXstream();  
        xs.processAnnotations(InputMessage.class);  
        xs.processAnnotations(OutputMessage.class);  
        // 将指定节点下的xml节点数据映射为对象  
        xs.alias("xml", InputMessage.class);  
        // 将流转换为字符串  
        List<String> contents = IOUtils.readLines(in, Charset.forName("UTF-8"));
        String xmlMsg = contents.stream().collect(Collectors.joining());
        // 将xml内容转换为InputMessage对象  
        InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());
        
        String servername = inputMsg.getToUserName();// 服务端  
        String custermname = inputMsg.getFromUserName();// 客户端  
        long createTime = inputMsg.getCreateTime();// 接收时间  
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间  
        
        // 取得消息类型  
        String msgType = inputMsg.getMsgType();
        String content = inputMsg.getContent();
        LOGGER.info("msgType=>{}",msgType);
        LOGGER.info("content=>{}",content);
        LOGGER.info("{} 说：{}",new Object[] {custermname,content});
        
	    if(MsgType.text.toString().equals(msgType)) {
	    		LOGGER.debug("开发者微信号：" + inputMsg.getToUserName());  
	        LOGGER.debug("发送方帐号：" + inputMsg.getFromUserName());  
	        LOGGER.debug("消息创建时间：" + inputMsg.getCreateTime() + new Date(createTime * 1000l));  
	        LOGGER.debug("消息内容：" + inputMsg.getContent());  
	        LOGGER.debug("消息Id：" + inputMsg.getMsgId());  
	
	        StringBuilder str = new StringBuilder();  
	        str.append("<xml>");  
	        str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>");  
	        str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>");  
	        str.append("<CreateTime>" + returnTime + "</CreateTime>");  
	        str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");  
	        str.append("<Content><![CDATA[你说的是：" + inputMsg.getContent() + "，吗？]]></Content>");  
	        str.append("</xml>");  
	        LOGGER.debug(str.toString());  
	        response.getWriter().write(str.toString());  
	    }
        
	}
	
//	@PostMapping("/main")
//	public void talk(HttpServletRequest request, HttpServletResponse response) throws IOException {
//		LOGGER.info("交互-{}", request.getRequestURL().toString());
//		// 处理接收消息  
//        List<String> contents = IOUtils.readLines(request.getInputStream(), Charset.forName("UTF-8"));
//        String xml = contents.stream().collect(Collectors.joining());
//        LOGGER.info("xml => {}", xml);
//        XMLSerializer xmlSerializer = new XMLSerializer();
//        String json = xmlSerializer.read(xml).toString();
//        LOGGER.info("json => {}", json);
//        JSONObject jsonObj = JSON.parseObject(json);
//        String content = jsonObj.getString("Content");
//        System.out.println(content);
//	}
	
}
